<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Http\Controllers\Controller;
use App\Models\AgentUser;
use App\Models\AutoLockTask;
use App\Models\FrontendUser;
use App\Models\Product;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class AutoLockTaskController extends Controller
{
    /** 锁单任务列表 */
    public function index()
    {
        /** @var AgentUser $user */
        $user = auth()->user();
        $query = AutoLockTask::query()->where('agent_id', $user->agent_id)
            ->when(request()->keyword, function ($q) {
                return $q->where('product_name', 'like', '%' . request()->keyword . '%');
            })
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /** 保存锁单任务信息 */
    public function store()
    {
        request()->validate([
            'product_id' => 'required',
            'locker_account' => 'required',
            'start_time' => 'required',
            'end_time' => 'required',
            'min_price' => 'required',
            'max_price' => 'required',
            'lock_minutes' => 'required',
        ]);

        /** @var AgentUser $user */
        $user = auth()->user();
        /** @var AutoLockTask $task */
        $task = get_entity(AutoLockTask::class);

        $productId = request()->product_id;
        /** @var Product $product */
        $product = Product::query()->where('agent_id', $user->agent_id)
            ->find($productId);
        if (!$product) {
            throw new AdminException('无效的商品ID');
        }

        /** @var FrontendUser $locker */
        $locker = FrontendUser::query()->where('agent_id', $user->agent_id)
            ->where('mobile', request()->locker_account)->first();
        if (!$locker) {
            throw new AdminException('无效的锁单人手机号');
        }

        $task->agent_id = $user->agent_id;
        $task->product_id = $productId;
        $task->product_name = $product->name;
        $task->contract_address = $product->contract_address;
        $task->start_time = request()->start_time;
        $task->end_time = request()->end_time;
        $task->min_price = toFen(request()->min_price);
        $task->max_price = toFen(request()->max_price);
        $task->lock_minutes = request()->lock_minutes;
        $task->locker_user_id = $locker->id;
        $task->locker_account = $locker->mobile;
        $task->save();
    }

    /** 删除锁单任务 */
    public function destroy($id)
    {
        AutoLockTask::destroy($id);
    }
}
